import 'package:flutter/material.dart';

class HoverDialog extends StatefulWidget {
  const HoverDialog({
    super.key,
    this.offset = const Offset(0, 100),
    this.hideDelay = const Duration(milliseconds: 100),
    required this.button,
    required this.menu,
    this.shape,
  });

  final Widget button; // 按钮
  final Widget menu;   // 悬浮菜单
  final ShapeBorder? shape;
  final Offset offset; // 偏移量
  final Duration hideDelay; // 延迟隐藏

  @override
  State<HoverDialog> createState() => _HoverDialogState();
}

class _HoverDialogState extends State<HoverDialog> {
  bool _isHoverButton = false;
  bool _isHoverMenu = false;

  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;

  void _showMenu() {
    if (_overlayEntry != null) return;
    _overlayEntry = OverlayEntry(
      builder: (context) {
        return CompositedTransformFollower(
          link: _layerLink,
          offset: widget.offset,
          showWhenUnlinked: false,
          child: Align(
            alignment: Alignment.topLeft,
            child: MouseRegion(
              onEnter: (_) {
                _isHoverMenu = true;
              },
              onExit: (_) {
                _isHoverMenu = false;
                _hideMenu();
              },
              child: widget.menu,
            ),
          ),
        );
      },
    );

    Overlay.of(context).insert(_overlayEntry!);
  }


  void _hideMenu() async {
    await Future.delayed(widget.hideDelay);
    if (_isHoverButton || _isHoverMenu) return;
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: MouseRegion(
        onEnter: (_) {
          _isHoverButton = true;
          _showMenu();
        },
        onExit: (_) {
          _isHoverButton = false;
          _hideMenu();
        },
        child: widget.button,
      ),
    );
  }
}
